package com.moonshineproject.plugin.haxe.haxecompiler.commands
{
	import __AS3__.vec.Vector;
	
	import com.moonshineproject.plugin.core.ExternalCommandBase;
	import com.moonshineproject.plugin.haxe.haxeproject.vo.HaXeProjectVO;
	import com.moonshineproject.plugin.project.event.RefreshTreeEvent;
	import com.moonshineproject.utils.FileUtil;
	
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.events.NativeProcessExitEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.utils.IDataInput;

	public class HaxeCompileCommand extends ExternalCommandBase
	{
		override public function get name():String { return "HaXe Compiler Plugin"; }
		
		protected var project:HaXeProjectVO;
		
		public function HaxeCompileCommand(executable:File)
		{
			super(executable, null);
		}
		
		public function compile(p:HaXeProjectVO, args:Vector.<String>):void
		{
			this.project = p;
			
			if (!p.swfOutput.path.exists)
			{
				FileUtil.createFile(p.swfOutput.path);
			}
			
			customInfo = new NativeProcessStartupInfo();
			customInfo.executable = executable;
			
			customInfo.arguments = args;
			customInfo.workingDirectory = p.folder;

			customProcess = new NativeProcess();
			customProcess.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, haxeError);
			customProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, haxeOutput);
			customProcess.addEventListener(NativeProcessExitEvent.EXIT, haxeExit);
			customProcess.start(customInfo);
		}
		
		protected function haxeError(event:ProgressEvent):void
		{
			//TODO: Parse error messages, format & output
			
			// Fetch output
			var output:IDataInput = (event.target as NativeProcess).standardOutput;
			var msg:String = output.readUTFBytes(output.bytesAvailable);
			
			// Make sure it's escaped
			error("%s", msg);
		}
		
		protected function haxeOutput(event:ProgressEvent):void
		{
			// Fetch output
			var output:IDataInput = (event.target as NativeProcess).standardError;
			var msg:String = output.readUTFBytes(output.bytesAvailable);
			
			// Make sure it's escaped
			print("%s", msg);
		}
		
		protected function haxeExit(event:NativeProcessExitEvent):void
		{
			if (event.exitCode == 0)
			{
				print("Done");
				
				// Update tree view to show new file
				dispatcher.dispatchEvent(
					new RefreshTreeEvent(project.swfOutput.path.parent)
				);
			}
			else
			{
				var msg:String = customProcess.standardError.readMultiByte(customProcess.standardError.bytesAvailable, 'us-ascii');
				error("%s", msg);
			}
			
			customProcess = null;
		}
		
	}
}